package com.xsmart.common.init;

import com.xsmart.common.constant.ApiInfoFieldConstant;
import com.xsmart.common.constant.RedisKeyConstant;
import com.xsmart.common.util.RedisUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 服务发现
 */
public class ServicesDiscoveryImpl {
    public void initServicesDiscovery(String applicationName, RedisUtil redisUtil, ApplicationContext applicationContext) {
        AbstractHandlerMethodMapping<RequestMappingInfo> objHandlerMethodMapping = (AbstractHandlerMethodMapping<RequestMappingInfo>) applicationContext.getBean("requestMappingHandlerMapping");
        Map<RequestMappingInfo, HandlerMethod> mapRet = objHandlerMethodMapping.getHandlerMethods();
        for (RequestMappingInfo requestMappingInfo : mapRet.keySet()) {
            Set<String> urls = requestMappingInfo.getPatternsCondition().getPatterns();
            for (String url : urls) {
                Map<String, String> urlInfo = new HashMap<>();
                urlInfo.put(ApiInfoFieldConstant.SERVICE_URI, url);
                urlInfo.put(ApiInfoFieldConstant.URL, "http://" + applicationName + url);
                urlInfo.put(ApiInfoFieldConstant.MODULAR, applicationName);
                try {
                    if (url != null && url.contains("/api/")) {
                        String[] serviceInfo = url.split("/");
                        if (serviceInfo.length >= 5) {
                            urlInfo.put(ApiInfoFieldConstant.VERSION, serviceInfo[2]);
                            urlInfo.put(ApiInfoFieldConstant.SERVICE_NAME, serviceInfo[3]);
                            urlInfo.put(ApiInfoFieldConstant.METHOD_NAME, serviceInfo[4]);
                            //增加例外api
                            if (url.contains("/ServiceListCtrlService/synApiCacheToDb")
                                    || url.contains("/ServiceListCtrlService/synApiDbToCache")
                                    || url.contains("/UserLoginService/login")
                                    || url.contains("/AdminLoginService/login")) {
                                urlInfo.put(ApiInfoFieldConstant.IS_LOGIN, "0");
                                urlInfo.put(ApiInfoFieldConstant.SERVICE_ID, "-2");
                            }
                        }
                    }
                } catch (Exception ignored) {

                }
                redisUtil.hmSetWithStrKey(RedisKeyConstant.API_INFO_PREFIX + url, urlInfo);
            }
            System.out.println(requestMappingInfo.getName());
        }
    }
}
